﻿using Admin2024.Domain.Entity.System;
using Admin2024.Domain.IDomainService.System.IUserService;
using Admin2024.Domain.Interface;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;

namespace Admin2024.Api.Filter
{
    public class CtmAuthorizationFilterAttribute : Attribute, IAuthorizationFilter
    {
        private readonly IJwtService jwtService;
        private readonly IRepository<AppUserRole> UserRoleRep;

        private readonly IRepository<AppRole> RoleRep;
        public CtmAuthorizationFilterAttribute(IJwtService jwtService,IRepository<AppUserRole> UserRoleRep, IRepository<AppRole> roleRep)
        {
            this.jwtService = jwtService;
            this.UserRoleRep = UserRoleRep;
            RoleRep = roleRep;
        }
        public async void OnAuthorization(AuthorizationFilterContext context)
        {
            var token = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault();

        
            // 检查token是否存在
            if (string.IsNullOrEmpty(token))
            {
                // 如果没有token，可以设置状态码为401（未授权）并返回错误信息
               context.Result = new UnauthorizedResult(); 
            }
            else
            {
                token = token.TrimStart().Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase);
                // 如果有token，可以进一步处理，比如验证token的有效性
                // 这里只是示例，具体验证逻辑需要根据实际情况实现
                var to =  jwtService.ValidateToken(token); // 假设这是验证token的方法
                if (to == null)
                {
                    context.Result = new UnauthorizedResult();
                }
                else
                {
                    var RoleName = to.Claims.First(item => item.Type == "RoleName").Value;

                    if (RoleName == null)
                    {
                        context.Result = new UnauthorizedResult();
                    }
                    else
                    {
                       
                        
                        if(RoleName == "超级管理员")
                        {

                        }
                        else
                        {
                            context.Result = new ForbidResult();
                        }



                        
                    }
                    
                }
            }
        }
    }
}
